<template>
  <div class="bg-gray-50 rounded-lg shadow p-4 sm:p-6">
    <h2 class="text-xl font-semibold text-gray-800 mb-6">评论 ({{ comments.length }})</h2>

    <!-- 发表评论 -->
    <div class="mb-8">
      <div class="flex items-start space-x-4">
        <img :src="currentUser.avatar" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
        <div class="flex-1">
          <textarea
            v-model="newComment"
            class="w-full p-3 bg-gray-100 border border-transparent rounded-lg focus:outline-none focus:ring-2 focus:ring-green-400 focus:bg-white transition-colors duration-200"
            placeholder="发表你的看法..."
            rows="3"
          ></textarea>
          <div class="flex justify-end mt-2">
            <button
              @click="addComment"
              class="bg-green-500 hover:bg-green-600 text-white font-semibold px-4 py-2 rounded-lg transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
              :disabled="!newComment.trim()"
            >
              发表评论
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <transition-group name="list" tag="div" class="space-y-6">
      <div v-for="comment in comments" :key="comment.id" class="transition-all duration-500">
        <!-- 主评论 -->
        <div class="flex space-x-4">
          <img :src="comment.author.avatar" alt="用户头像" class="w-10 h-10 rounded-full object-cover flex-shrink-0">
          <div class="flex-1">
            <div class="flex items-baseline">
              <h3 class="font-semibold text-gray-900">{{ comment.author.nickname }}</h3>
              <span class="text-xs text-gray-500 ml-2">{{ comment.author.schoolName }}</span>
            </div>
            <p class="text-gray-700 mt-1">{{ comment.content }}</p>
            <div class="flex items-center text-sm text-gray-500 mt-2 space-x-4">
              <span>{{ formatTime(comment.createTime) }}</span>
              <div class="flex items-center cursor-pointer group" @click="likeComment(comment)">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 group-hover:text-red-500 transition-colors duration-200" :class="{'text-red-500 fill-current': comment.isLiked}" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                </svg>
                <span class="ml-1 group-hover:text-red-500 transition-colors duration-200">{{ comment.likes }}</span>
              </div>
              <div class="cursor-pointer group" @click="startReply(comment)">
                <span class="font-semibold text-gray-500 group-hover:text-green-500 transition-colors duration-200">回复</span>
              </div>
            </div>

            <!-- 回复输入框 -->
            <transition name="fade">
              <div v-if="replyingTo && replyingTo.id === comment.id" class="mt-4">
                <div class="flex items-start space-x-3">
                  <img :src="currentUser.avatar" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
                  <div class="flex-1">
                    <textarea
                      ref="replyTextarea"
                      v-model="replyContent"
                      class="w-full border border-gray-300 rounded-lg p-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-400"
                      :placeholder="`回复 ${replyingTo.author.nickname}`"
                      rows="2"
                    ></textarea>
                    <div class="flex justify-end items-center mt-2 space-x-2">
                      <button
                        @click="cancelReply"
                        class="text-sm text-gray-600 hover:text-gray-800 px-3 py-1 rounded-md"
                      >
                        取消
                      </button>
                      <button
                        @click="addReply(comment)"
                        class="bg-green-500 hover:bg-green-600 text-white px-4 py-1.5 rounded-lg text-sm font-semibold transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                        :disabled="!replyContent.trim()"
                      >
                        回复
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </transition>
          </div>
        </div>

        <!-- 二级评论 -->
        <div v-if="comment.replies && comment.replies.length > 0" class="pl-14 mt-4 space-y-4">
          <div v-for="reply in comment.replies" :key="reply.id" class="flex space-x-3">
            <img :src="reply.author.avatar" alt="用户头像" class="w-8 h-8 rounded-full object-cover flex-shrink-0">
            <div class="flex-1">
              <div class="flex items-baseline">
                <h3 class="font-semibold text-gray-900 text-sm">{{ reply.author.nickname }}</h3>
                <span class="text-xs text-gray-500 ml-2">{{ reply.author.schoolName }}</span>
              </div>
              <p class="text-gray-700 text-sm mt-1">
                <span v-if="reply.replyTo" class="text-green-500 font-medium">@{{ reply.replyTo.nickname }} </span>
                {{ reply.content }}
              </p>
              <div class="flex items-center text-xs text-gray-500 mt-2 space-x-4">
                <span>{{ formatTime(reply.createTime) }}</span>
                <div class="flex items-center cursor-pointer group" @click="likeReply(comment, reply)">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 group-hover:text-red-500 transition-colors duration-200" :class="{'text-red-500 fill-current': reply.isLiked}" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                     <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                  </svg>
                  <span class="ml-1 group-hover:text-red-500 transition-colors duration-200">{{ reply.likes }}</span>
                </div>
                <div class="cursor-pointer group" @click="startReply(comment, reply)">
                  <span class="font-semibold text-gray-500 group-hover:text-green-500 transition-colors duration-200">回复</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition-group>

    <!-- 无评论时显示 -->
    <div v-if="comments.length === 0" class="text-center py-10 text-gray-500">
      <p class="text-lg">暂无评论</p>
      <p class="mt-1">快来发表第一条评论吧！</p>
    </div>
  </div>
</template>

<script>
import { commentData } from '@/mock/comment/commentData';
import userAvatar from '@/assets/default/userAvatar.jpg';

export default {
  name: 'CommentSection',
  props: {
    postId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      comments: [],
      newComment: '',
      replyingTo: null,
      replyContent: '',
      currentUser: {
        id: 'currentUser',
        nickname: '当前用户',
        avatar: userAvatar,
        schoolName: '示例大学'
      }
    };
  },
  created() {
    this.loadComments();
  },
  methods: {
    formatTime(value) {
      if (!value) return '';
      const date = new Date(value);
      const now = new Date();
      const diff = now.getTime() - date.getTime();
      const minute = 1000 * 60;
      const hour = minute * 60;
      const day = hour * 24;

      if (diff < minute) {
        return '刚刚';
      } else if (diff < hour) {
        return `${Math.floor(diff / minute)}分钟前`;
      } else if (diff < day) {
        return `${Math.floor(diff / hour)}小时前`;
      } else {
        return date.toLocaleDateString();
      }
    },
    // 加载评论
    loadComments() {
      // 这里模拟从API获取评论数据
      // 实际应用中，应该根据postId从后端获取评论
      this.comments = JSON.parse(JSON.stringify(commentData));
    },

    // 添加评论
    addComment() {
      if (!this.newComment.trim()) return;

      const now = new Date();
      const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;

      const newComment = {
        id: `comment-${Date.now()}`,
        content: this.newComment,
        createTime: formattedDate,
        likes: 0,
        isLiked: false,
        author: this.currentUser,
        replies: []
      };

      this.comments.unshift(newComment);
      this.newComment = '';

      // 实际应用中，应该将评论发送到后端
      console.log('添加评论:', newComment);
    },

    // 点赞评论
    likeComment(comment) {
      if (comment.isLiked) {
        comment.likes--;
        comment.isLiked = false;
      } else {
        comment.likes++;
        comment.isLiked = true;
      }

      // 实际应用中，应该将点赞状态发送到后端
      console.log('点赞评论:', comment.id, '点赞状态:', comment.isLiked);
    },

    // 点赞回复
    likeReply(parentComment, reply) {
      if (reply.isLiked) {
        reply.likes--;
        reply.isLiked = false;
      } else {
        reply.likes++;
        reply.isLiked = true;
      }

      // 实际应用中，应该将点赞状态发送到后端
      console.log('点赞回复:', reply.id, '点赞状态:', reply.isLiked);
    },

    // 开始回复
    startReply(comment, reply = null) {
      const newAuthor = reply ? reply.author : comment.author;
      const isCurrentlyReplying = this.replyingTo && 
                                  this.replyingTo.id === comment.id &&
                                  this.replyingTo.author.id === newAuthor.id;

      if (isCurrentlyReplying) {
        this.cancelReply();
      } else {
        this.replyingTo = {
          id: comment.id,
          author: newAuthor
        };
        this.replyContent = '';
        this.$nextTick(() => {
          if (this.$refs.replyTextarea && this.$refs.replyTextarea.focus) {
            this.$refs.replyTextarea.focus();
          }
        });
      }
    },

    // 取消回复
    cancelReply() {
      this.replyingTo = null;
      this.replyContent = '';
    },

    // 添加回复
    addReply(comment) {
      if (!this.replyContent.trim() || !this.replyingTo) return;

      const now = new Date();
      const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;

      const newReply = {
        id: `reply-${Date.now()}`,
        content: this.replyContent,
        createTime: formattedDate,
        likes: 0,
        isLiked: false,
        author: this.currentUser,
        replyTo: {
          id: this.replyingTo.author.id,
          nickname: this.replyingTo.author.nickname
        }
      };

      comment.replies.push(newReply);
      this.replyingTo = null;
      this.replyContent = '';

      // 实际应用中，应该将回复发送到后端
      console.log('添加回复:', newReply);
    }
  }
};
</script>

<style scoped>

</style>
